﻿using System;
using DevelopTool.Common;
using DevelopTool.Model.CodeModels;
using DevelopTool.Model.SchedulerModels;
using Quartz;
using Sunny.UI;

namespace DevelopTool.Bll.SchedulerBlls.Jobs
{
    /// <summary>
    /// 定时任务-代码
    /// </summary>
    public class CodeJob : IJob
    {
        private SchedulerBll schedulerBll;
        private Scheduler_CodeBll scheduler_CodeBll;
        private SchedulerLogBll schedulerLogBll;

        public CodeJob()
        {
            schedulerBll = new SchedulerBll();
            scheduler_CodeBll = new Scheduler_CodeBll();
            schedulerLogBll = new SchedulerLogBll();
        }

        public void Execute(IJobExecutionContext context)
        {
            Scheduler scheduler = null;
            try
            {
                scheduler = context.JobDetail.JobDataMap.Get("scheduler") as Scheduler;//任务参数
                Scheduler_Code scheduler_Code = scheduler_CodeBll.GetBySchedulerId(scheduler.Id);

                Code code = scheduler_Code.Code;
                code.MainCodeText = code.MainCodeText.GZipDecompress();
                code.CustomCodeText = code.CustomCodeText.GZipDecompress();
                var result = CSScriptHelper.ExecuteCode(code.MainCodeText, code.CustomCodeText, code.LibraryReference);

                schedulerLogBll.Save(new SchedulerLog() { SchedulerId = scheduler.Id, Result = result.Item2.ToString() });//写日志

                if (Setting.System.SendMsgModule.Contains("Scheduler"))
                    FeiShuMsgHelper.SendCardMsgAsync($"执行结果：{result.Item2.ToString()}", $"定时任务[代码]-{scheduler.NodeName}");
            }
            catch (Exception ex)
            {
                schedulerLogBll.Save(new SchedulerLog() { SchedulerId = scheduler.Id, Exception = ex.Message });
                LogHelper.WriteErrLog(ex);
            }
            finally
            {
                //设置任务执行次数
                if (scheduler != null)
                {
                    scheduler = schedulerBll.GetById(scheduler.Id);
                    scheduler.RunNumber++;
                    schedulerBll.Save(scheduler);
                }
            }
        }

    }
}
